using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace QTool.NetFrame
{
    public class FixCoroutineList
    {
        private LinkedList<IEnumerator> coroutineList = new LinkedList<IEnumerator>();
        public IEnumerator StartCoroutine(IEnumerator ie)
        {
            coroutineList.AddLast(ie);
			return ie;

		}

        public void StopCoroutine(IEnumerator ie)
        {
            try
            {
                coroutineList.Remove(ie);
            }
            catch (Exception e) { Debug.LogError(e.ToString()); }
        }
    
        bool Update(IEnumerator ie)
        {
            bool ret = true;

            if (ie.Current is IEnumerator childIe)
            {
                if (Update(childIe)) return true;
            }
            if (ie.Current is IWait iWait)
            {
                if (iWait.Update())
                {
                    iWait.Recover();
                    ret = ie.MoveNext();
                }
            }
            else
            {
                ret = ie.MoveNext();
            }

            return ret;
        }
        public void UpdateAll()
        {
            var node = coroutineList.First;
            while (node != null)
            {
                IEnumerator ie = node.Value;
                if (!Update(ie))
                {
                    coroutineList.Remove(node);
                }
                node = node.Next;
            }
        }
    }
    public interface IWait
    {
        bool Update();
        void Recover();
    }
    public class WaitTrue: PoolObject<WaitTrue>,IWait
    {
        public System.Func<bool> func;
        public static WaitTrue Get(System.Func<bool> func)
        {
            var wait = Get();
            wait.func = func;
            return wait;
        }

        public override void OnPoolRecover()
        {
            func = null;
        }

        public override void OnPoolReset()
        {
        }

        public bool Update()
        {
            if (func == null) return true;
            return func.Invoke();
        }
    }
    public class WaitFixSeconds :PoolObject<WaitFixSeconds> ,IWait
    {
        public Fix64 time {  set; get; }
        public static WaitFixSeconds Get(Fix64 time)
        {
            var wait= Get();
            wait.time = time;

            return wait;
        }
        public bool Update()
        {
            time -= QNetManager.Instance.DelatTime;
            return time<=0;
        }

        public override void OnPoolRecover()
        {
            
        }

        public override void OnPoolReset()
        {
        }
    }
}
